import { defineStore } from "pinia";
import { useArticleStore } from "./article";
import { saveHistory, getArticleHistory } from "@/services/historyService";

export const useEditorStore = defineStore("editor", () => {
  const articleStore = useArticleStore();
  const content = ref("");
  const isPreview = ref(false);
  const history = ref<string[]>([]);
  const historyIndex = ref(-1);
  const canUndo = ref(false);
  const canRedo = ref(false);
  const isUpdating = ref(false);
  const isLoadingHistory = ref(false);
  let lastLoadedArticleId = "";

  // 加载文章历史记录
  const loadArticleHistory = async () => {
    if (
      !articleStore.activeArticle ||
      lastLoadedArticleId === articleStore.activeArticle ||
      isLoadingHistory.value
    ) {
      return;
    }

    try {
      isLoadingHistory.value = true;
      lastLoadedArticleId = articleStore.activeArticle;

      const records = await getArticleHistory(articleStore.activeArticle);
      history.value = records
        .sort((a, b) => a.timestamp - b.timestamp)
        .map((r) => r.content);

      historyIndex.value = history.value.length - 1;
      content.value = history.value[historyIndex.value] || "";
      updateHistoryState();
    } finally {
      isLoadingHistory.value = false;
    }
  };

  // 更新历史状态
  const updateHistoryState = () => {
    // 只更新按钮状态
    canUndo.value = historyIndex.value > 0;
    canRedo.value = historyIndex.value < history.value.length - 1;
  };

  const setContent = async (newContent: string, force = false) => {
    if (
      !articleStore.activeArticle ||
      content.value === newContent ||
      (isUpdating.value && !force)
    )
      return;

    try {
      isUpdating.value = true;

      // 更新文章内容，但不触发历史记录
      await articleStore.updateArticleContent(newContent);

      // 保存历史记录
      await saveHistory(articleStore.activeArticle, newContent);

      // 更新本地历史状态
      if (historyIndex.value < history.value.length - 1) {
        history.value = history.value.slice(0, historyIndex.value + 1);
      }
      history.value.push(newContent);
      historyIndex.value = history.value.length - 1;

      content.value = newContent;
      updateHistoryState();
    } finally {
      isUpdating.value = false;
    }
  };

  const undo = async () => {
    if (historyIndex.value > 0 && !isUpdating.value) {
      try {
        isUpdating.value = true;
        console.log("Before undo:", historyIndex.value);
        historyIndex.value--;

        content.value = history.value[historyIndex.value];

        // 更新文章内容，但不触发历史记录
        await articleStore.updateArticleContent(content.value);

        // 更新按钮状态
        updateHistoryState();
      } finally {
        isUpdating.value = false;
      }
    }
  };

  const redo = async () => {
    if (historyIndex.value < history.value.length - 1 && !isUpdating.value) {
      try {
        isUpdating.value = true;
        historyIndex.value++;

        content.value = history.value[historyIndex.value];

        // 更新文章内容，但不触发历史记录
        await articleStore.updateArticleContent(content.value);

        // 更新按钮状态
        updateHistoryState();
      } finally {
        isUpdating.value = false;
      }
    }
  };

  // 监听文章切换
  watch(
    () => articleStore.activeArticle,
    (newId) => newId && loadArticleHistory()
  );

  const togglePreview = () => {
    isPreview.value = !isPreview.value;
  };

  // 添加强制清空方法
  const forceClearContent = async () => {
    isUpdating.value = false; // 先重置更新状态
    await setContent("", true); // 使用强制模式
  };

  return {
    content,
    isPreview,
    canUndo,
    canRedo,
    setContent,
    undo,
    redo,
    togglePreview,
    loadArticleHistory,
    forceClearContent,
  };
});
